package com.fengziyu.lib_recyclerview_fzy.mvvm

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

open class BaseViewModel: ViewModel() {
    private val _loading = MutableLiveData<Boolean>()
    val loading: LiveData<Boolean> get()  = _loading

    private val _error = MutableLiveData<String?>()

    val error: LiveData<String?> get() = _error

    private fun setLoading(isLoading: Boolean){
        _loading.value = isLoading
    }
    private fun setError(errorMessage: String?){
        _error.value = errorMessage
    }

    protected fun <T> executeRequest(call: Call<T> , onSuccess: (T)->Unit){
        setLoading(true)
        call.enqueue(object : Callback<T>{
            override fun onResponse(call: Call<T>, response: Response<T>) {
                setLoading(true)
                if(response.isSuccessful){
                    response.body()?.let { onSuccess(it) }
                }else{
                    setError("请求失败${response.message()}")
                }
            }

            override fun onFailure(call: Call<T>, t: Throwable) {
                setLoading(false)
                setError("请求失败${t.message}")
            }

        })
    }
}